package com.heima.leadnews.artlite.listener;

import com.heima.leadnews.artlite.service.ApArticleService;
import com.heima.model.common.Behavior.KafkaStream;
import com.heima.model.common.article.pojo.ApArticle;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class SinkTopicListener {
    @Autowired
    private ApArticleService apArticleService;

    @KafkaListener(topics = KafkaStream.ARTIC_SINK)
    public void receiveMessage(ConsumerRecord<String, String> record) {
        String[] split = record.key().split(":");
        String value = record.value();
        if (split[0].equals("like")) {
            Integer likes = 0;
            //判断时点赞还是取消
            if (split[2].equals("0")) {
                likes += Integer.parseInt(value);
            } else {
                likes -= Integer.parseInt(value);
            }

            ApArticle apArticle = apArticleService.getById(split[1]);
            apArticle.setLikes(apArticle.getLikes() + likes);
            apArticleService.updateById(apArticle);

        } else if (split[0].equals("read")) {

            ApArticle apArticle = apArticleService.getById(split[1]);
            apArticle.setViews(apArticle.getViews() + Integer.parseInt(value));
            apArticleService.updateById(apArticle);
        }
    }
}